
const app = getApp()
const { request } = require('../../utils/request.js');
const api = require('../../utils/api.js');
Page({
  data: {
    keyword: '',
    results: [],
    hasError: false,
    errorMsg: '',
    emptyResult: false,
    showBackToTop: false,
    scrollTop: 0,
    showLoading: true,
    feedback_status: true,
    pageTop: 0,
    loading: true,  // 是否显示骨架屏
    data: null,     // 展示数据
    timer: null,   // 定时器ID
    g_loading: false,

  },

  onLoad() {
    const startTime = Date.now();
    
    this.pollInterval = setInterval(() => {
      const cache = wx.getStorageSync('bPageData');
      if (cache) {
        try {
          const cacheObj = JSON.parse(decodeURIComponent(cache));
          if ((cacheObj.data)) {

            this.processResults(cacheObj.data)
            clearInterval(this.pollInterval);
            this.setData({
              loading: false,
              hasError: false,
              errorMsg: '',
              g_loading: false
            });
            return;
          } else {
            clearInterval(this.pollInterval);
            this.setData({
              loading: false,
              hasError: true,
              errorMsg: '没有搜到题目',
              g_loading: false
            });
          }
        } catch (e) {
          this.setData({
            loading: false,
            hasError: true,
            errorMsg: '解析数据失败',
            g_loading: false
          });
          // 解析失败，忽略，继续轮询
          console.warn('解析缓存数据失败', e);
        }
      }
      if ((Date.now() - startTime > 5000)) {
        this.setData({ g_loading: true })
      }
      if (Date.now() - startTime > 20000) {
        clearInterval(this.pollInterval);
      }
    }, 10);
  },
  isValidData(data) {
    return true
  },
  showSkeleton() {
    this.setData({
      results: null,
      loading: true,
      hasError: false,
      errorMsg: ''
    });
  },
  onUnload() {
    if (this.pollInterval) {
      clearInterval(this.pollInterval);
    }
  },
  // 处理解析结果数据的方法，封装你原来的逻辑
  processResults: function (parsedData) {
    const that = this;

    if (parsedData && parsedData.keyword) {
      that.setData({
        keyword: parsedData.keyword
      });

      if (parsedData.results && parsedData.results.length > 0) {
        const processedResults = parsedData.results.map(item => {
          item.answer = item.answer !== undefined && item.answer !== null ? String(item.answer) : '';
          item.answerList = that.formatAnswerToArray(item.answer);
          item.correctOptionsText = [];

          if (item.answerList.includes('1') && item.optionA) item.correctOptionsText.push(item.optionA);
          if (item.answerList.includes('2') && item.optionB) item.correctOptionsText.push(item.optionB);
          if (item.answerList.includes('3') && item.optionC) item.correctOptionsText.push(item.optionC);
          if (item.answerList.includes('4') && item.optionD) item.correctOptionsText.push(item.optionD);

          item.showAnalysis = false;
          item.copied = false;

          return item;
        });

        that.setData({
          results: processedResults,
          emptyResult: false,
          loading: false
        });
      } else {
        that.setData({
          emptyResult: true,
          loading: false
        });
      }
    } else {
      that.setData({
        hasError: true,
        errorMsg: '数据格式错误',
        loading: false
      });
    }
  },

  // 主动请求数据，20秒超时调用
  fetchData: function () {
    const that = this;

    wx.request({
      url: 'https://your.api/data', // 替换成你自己的接口地址
      method: 'GET',
      success: res => {
        if (res.data) {
          that.processResults(res.data);
          that.setData({
            loading: false
          });
          try {
            wx.setStorageSync('bPageData', encodeURIComponent(JSON.stringify(res.data)));
          } catch (e) { }
        } else {
          that.setData({
            loading: false,
            emptyResult: true
          });
        }
      },
      fail: () => {
        that.setData({
          loading: false
        });
      }
    });
  },

  onUnload() {
    // 页面卸载清理定时器
    if (this.data.timer) {
      clearTimeout(this.data.timer);
    }
  },

  /**
   * 处理页面滚动事件
   */
  handlePageScroll(e) {
    // 滚动超过500rpx显示返回顶部按钮
    const showBackToTop = e.scrollTop > 500;
    if (showBackToTop !== this.data.showBackToTop) {
      this.setData({
        showBackToTop,
        pageTop: e.scrollTop
      });
    }
  },

  onReady() {
    setTimeout(() => {
      this.setData({
        showLoading: false
      })
    }, 300)
  },

  /**
   * 搜索题目
   */
  searchQuestions(keyword) {
    if (!keyword) return;

    this.setData({
      loading: true,
      hasError: false,
      errorMsg: '',
      emptyResult: false
    });

    // 模拟API请求，实际项目中应替换为真实请求
    wx.request({
      url: 'https://api.example.com/search',
      data: { keyword },
      success: (res) => {
        // 处理成功响应
        setTimeout(() => {
          // 模拟数据
          const results = this.data.results || [];

          this.setData({
            isLoading: false,
            results: results,
            emptyResult: results.length === 0
          });
        }, 1500);
      },
      fail: (err) => {
        // 处理错误
        this.setData({
          isLoading: false,
          hasError: true,
          errorMsg: '搜索失败，请稍后重试'
        });
      }
    });
  },

  /**
   * 重试搜索
   */
  retrySearch() {
    this.searchQuestions(this.data.keyword);
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 切换显示/隐藏解析
   */
  toggleAnalysis(e) {
    const index = e.currentTarget.dataset.index;
    const results = [...this.data.results];
    results[index].showAnalysis = !results[index].showAnalysis;

    this.setData({
      results
    });
  },

  /**
   * 复制答案
   */
  copyAnswer(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.results[index];

    if (!item || !item.correctOptionsText) {
      return wx.showToast({
        title: '无法复制答案',
        icon: 'none'
      });
    }

    // 组合答案文本
    let answerText = '';
    item.correctOptionsText.forEach((text, i) => {
      answerText += (i > 0 ? '\n' : '') + text;
    });

    // 如果有解析，也一并复制
    if (item.solve) {
      answerText += '\n\n【解析】\n' + item.solve;
    }

    wx.setClipboardData({
      data: answerText,
      success: () => {
        // 复制成功后更新状态
        const results = [...this.data.results];
        results[index].copied = true;
        this.setData({ results });

        // 1.5秒后重置状态
        setTimeout(() => {
          const results = [...this.data.results];
          results[index].copied = false;
          this.setData({ results });
        }, 1500);

        wx.showToast({
          title: '答案已复制',
          icon: 'success'
        });
      }
    });
  },

  /**
   * 图片预览
   */
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url
    });
  },

  /**
   * 反馈错题
   */
  feedback() {
    wx.showModal({
      title: '反馈错题',
      content: '确认要反馈此题目有误吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '反馈成功，谢谢！',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 返回顶部
   */
  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },

  // 将答案格式化为数组
  formatAnswerToArray: function (answer) {
    if (!answer) return [];

    // 处理答案中可能有的空格和中文逗号
    answer = String(answer).replace(/，/g, ',').replace(/\s+/g, '');

    // 将答案分割成数组
    return answer.split(',');
  },

  // 格式化答案，将数字转换为字母
  formatAnswer: function (answer) {
    if (!answer) return '';

    // 处理答案中可能有的空格和中文逗号
    answer = String(answer).replace(/，/g, ',').replace(/\s+/g, '');

    // 将答案分割成数组
    const parts = answer.split(',');

    // 转换每个数字为对应字母
    const letters = parts.map(num => {
      switch (num) {
        case '1': return 'A';
        case '2': return 'B';
        case '3': return 'C';
        case '4': return 'D';
        default: return num; // 保留不是1-4的原始值
      }
    });
    // 返回转换后的字母，用逗号和空格连接
    return letters.join(', ');
  },
})